package com.sinodata.ns.sv;

import com.sinodata.ns.cell.JLBDInfo;
import com.sinodata.ns.cell.JLBDManager;
import com.sinodata.ns.sv.impl.ISupervisorImpl;

import jt.classic.system.ISystemException;
import jt.classic.system.SimpleManager;
import jt.classic.system.user.IUser;
import jt.classic.system.user.UserCenter;
import jt.classic.system.user.UserManager;
import jt.classic.system.utils.AnnexTool;

import org.limp.basework.Column;

import org.limp.mine.DataTrimmerI.DataItemList;
import org.limp.mine.StringTool;
import org.limp.mine.annex.AnnexInfo;

import java.sql.Connection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 监理信息管理者
 *
 * @author mido
 *
 */
public class SupervisorManager extends SimpleManager {
    public SupervisorManager(Connection conn) {
        super(conn);
    }

    /**
     * 根据主键ID获取监理实例
     * @param id 主键ID
     * @return ISupervisor
     * @throws ISystemException
     */
    public ISupervisor getSupervisorById(String id) throws ISystemException {
        String sql = "SELECT * FROM APP_NS_JLRY WHERE NU_ID = ?";

        DataItemList dil = this.trimmerI.createDIL();

        dil.set(id);

        Map info = this.trimmerI.searchSingleData(sql, dil);

        ISupervisor sv = this.initSupervisor(info);

        if (sv == null) {
            throw new ISystemException("not found Supervisor by id['" + id +
                "'].");
        }

        return sv;
    }

    /**
     *
     * @param info
     * @return
     * @throws ISystemException
     */
    private ISupervisor initSupervisor(Map info) throws ISystemException {
        ISupervisor sv = null;

        if (info != null) {
            String userId = (String) info.get("NU_USERID");

            UserCenter uc = UserCenter.getInstance();

            IUser user = uc.getUserById(userId);

            if (user == null) {
                throw new ISystemException(
                    "not found Supervisor's user by id['" + info.get("NU_ID") +
                    "'].");
            }

            info.put("USER", user);

            String bdid = StringTool.checkString(info.get("NU_BDID"));

            if (!bdid.equals("") && !bdid.equals("0")) {
                JLBDManager jm = new JLBDManager(this.conn);

                JLBDInfo jlbd = jm.getJLBDInfoById(bdid);

                info.put("JLBDINFO", jlbd);
            }

            sv = new ISupervisorImpl();

            sv.reload(info);
        }

        return sv;
    }

    /**
     *
     * @param userId
     * @return
     * @throws ISystemException
     */
    public ISupervisor getSupervisorByUserId(String userId)
        throws ISystemException {
        String sql = "SELECT * FROM APP_NS_JLRY WHERE NU_USERID = ?";

        DataItemList dil = this.trimmerI.createDIL();

        dil.set(userId);

        Map info = this.trimmerI.searchSingleData(sql, dil);

        ISupervisor sv = this.initSupervisor(info);

        if (sv == null) {
            throw new ISystemException("not found Supervisor by userId['" +
                userId + "'].");
        }

        return sv;
    }

    /**
     *
     * @param userId
     * @param code
     * @return
     * @throws ISystemException
     */
    public ISupervisor getSupervisorByUserCode(String userId, String code)
        throws ISystemException {
        String sql = "SELECT * FROM APP_NS_JLRY WHERE NU_USERID = ? AND NU_MOBILECODE = ?";

        DataItemList dil = this.trimmerI.createDIL();

        dil.set(userId);
        dil.set(code);

        Map info = this.trimmerI.searchSingleData(sql, dil);

        ISupervisor sv = this.initSupervisor(info);

        /*if (sv == null) {
            throw new ISystemException("not found Supervisor by userId['" +
                userId + "'],code['" + code + "'].");
        }*/
        return sv;
    }

    /**
     *
     * @param code
     * @return
     * @throws ISystemException
     */
    public ISupervisor getSupervisorByCode(String code)
        throws ISystemException {
        String sql = "SELECT * FROM APP_NS_JLRY WHERE NU_MOBILECODE = ?";

        DataItemList dil = this.trimmerI.createDIL();

        dil.set(code);

        Map info = this.trimmerI.searchSingleData(sql, dil);

        ISupervisor sv = this.initSupervisor(info);

        if (sv == null) {
            throw new ISystemException("not found Supervisor by code['" + code +
                "'].");
        }

        return sv;
    }

    /**
     * 根据监理标段主键ID获取监理实例
     * @param id 主键ID
     * @return List
     * @throws ISystemException
     */
    public List getSupervisorsByJLBD(String id) throws ISystemException {
        String sql = "SELECT NU_ID FROM APP_NS_JLRY WHERE NU_BDID = ?";

        DataItemList dil = this.trimmerI.createDIL();

        dil.set(id);

        List list = this.trimmerI.searchMultiData(sql, dil);

        if ((list != null) && !list.isEmpty()) {
            for (int i = 0; i < list.size(); i++) {
                Map info = (Map) list.get(i);
                String nuid = (String) info.get("NU_ID");

                ISupervisor sv = this.getSupervisorById(nuid);

                list.set(i, sv);
            }
        }

        return list;
    }

    /**
     * 校验监理人员身份合法性
     * @param logid 登录帐号
     * @param pwd 登录密码
     * @param code 设备编号
     * @return ISupervisor
     */
    public ISupervisor checkSupervisor(String logid, String pwd, String code)
        throws ISystemException {
        UserManager um = new UserManager(this.conn);

        IUser user = um.logcheck(logid, pwd);

        ISupervisor sv = null;

        if ((user != null) && (user.iflag() == 0)) {
            sv = this.getSupervisorByUserCode(user.id(), code);

            if (sv == null) {
                throw new ISystemException("not found Supervisor by userId['" +
                    user.id() + "'],code['" + code + "'].");
            }
        } else {
            throw new ISystemException("Illegal access [logid:'" + logid +
                "', pwd:'" + pwd + "'].");
        }

        return sv;
    }

    /**
    * 设备已被占用
    * @param code
    * @return boolean
    */
    public boolean codeInUserd(String code) {
        String sql = "SELECT NU_ID FROM APP_NS_JLRY WHERE NU_MOBILECODE = ?";

        DataItemList dil = this.trimmerI.createDIL();

        dil.set(code);

        boolean rnt = this.trimmerI.haveMoreData(sql, dil);

        return rnt;
    }

    /**
     * 删除监理人员
     * @param sv
     */
    public void delete(ISupervisor sv) throws ISystemException {
        StringBuffer sb = new StringBuffer();

        sb.append("DELETE FROM APP_NS_JLRY WHERE NU_ID = ?");

        List dilList = new ArrayList();

        DataItemList dil = this.trimmerI.createDIL();

        dil.set(sv.id());

        dilList.add(dil);

        if (this.trimmerI.executeBatch(sb.toString(), dilList)) {
        	/*身份为监理人员时,需删除关联的系统用户信息*/
            if ((sv.iuser().irating() == 1) || (sv.iuser().irating() == 2)) {
                UserManager um = new UserManager(conn);

                um.delete(sv.iuser().id());
            }
        } else {
            throw new ISystemException("delete supervisor[" + sv.id() +
                "] error.");
        }
    }

    /**
     * 监理人员状态更新
     * @param id
     * @param flag
     */
    public void flag(ISupervisor sv, int flag) {
        UserManager um = new UserManager(conn);

        if (flag == -1) {
            um.disabled(sv.iuser().id());
        } else if (flag == 0) {
            um.abled(sv.iuser().id());
        }
    }

    /**
     * 获取监理人员考勤信息
     * @param userId 考勤人员ID
     * @param date 考勤日期 (null for all date)
     * @param tp (null for all type)
     * @return List
     */
    public List getKaoqinInfoBySupervisor(String userId, String date, int tp) {
        String sql = "SELECT * FROM APP_NS_KQ WHERE K_USERID = ?";

        DataItemList dil = this.trimmerI.createDIL();

        dil.set(userId);

        if (date != null) {
            sql += " AND K_CTIME LIKE ?";

            dil.set(date + "%");
        }

        if (tp > -1) {
            sql += " AND K_TYPE = ?";

            dil.set(tp);
        }

        sql += " ORDER BY K_TYPE ASC";

        List list = this.trimmerI.searchMultiData(sql, dil);

        if ((list != null) && !list.isEmpty()) {
            AnnexTool annexTool = new AnnexTool(conn);

            for (int i = 0; i < list.size(); i++) {
                Map temp = (Map) list.get(i);

                String id = (String) temp.get("K_ID");

                AnnexInfo[] annexs = annexTool.getAnnexs(id, "APP_NS_KQ");

                if ((annexs != null) && (annexs.length > 0)) {
                    List annexList = new ArrayList();

                    for (int kk = 0; kk < annexs.length; kk++) {
                        AnnexInfo ai = annexs[kk];
                        Map annexInfo = new HashMap();
                        annexInfo.put("id", ai.getID());
                        annexInfo.put("name", ai.getName());
                        annexInfo.put("type", ai.getType());
                        annexInfo.put("folder", ai.getRepository());
                        annexInfo.put("url", ai.getLinkString());
                        annexList.add(annexInfo);
                    }

                    temp.put("K_ZHAOPIAN", annexList);
                }
            }
        }

        return list;
    }

    /**
     * 获取监理人员轨迹信息
     * @param userId 考勤人员ID
     * @param date 考勤日期 (null for all date)
     * @param tp (null for all type)
     * @return List
     */
    public List getTrackInfoBySupervisor(String userId, String date) {
        String sql = "SELECT * FROM APP_NS_TRACK WHERE USERID = ?";

        DataItemList dil = this.trimmerI.createDIL();

        dil.set(userId);

        if (date != null) {
            sql += " AND CTIME LIKE ?";

            dil.set(date + "%");
        }

        sql += " ORDER BY CTIME DESC";

        return this.trimmerI.searchMultiData(sql, dil);
    }
}
